

var userList = [];


initializTheHTMLPage();

// 初始化HTML页面
function initializTheHTMLPage() {
    // 用户1
    const item1 = new UserItem(1, "超级管理员", "admin", 1, "2020-12-14 18:59:18");
    userList.push(item1);

    // 用户2
    const item2 = new UserItem(2, "普通角色", "admin", 2, "2020-12-14 18:59:18");
    userList.push(item2);

    // 用户3
    const item3 = new UserItem(3, "普通角色", "admin", 3, "2020-12-14 18:59:18");
    userList.push(item3);

    for (let i = 0; i < userList.length; i++) {
        let item = userList[i];
        addLineData(item);
    }
}


/**
 * 根据userItem模型添加一条用户数据
 * @param {*} userItem 用户对应的数据模型
 */
function addLineData(userItem) {
    var tbody = document.querySelectorAll('tbody')[0];
    var tr = document.createElement('tr');
    tbody.appendChild(tr);
    var td = document.createElement('td');
    td.innerHTML = '<input type="checkbox">';
    tr.appendChild(td);

    var item = userItem;
    for (let index = 0; index < 5; index++) {
        let value = "";
        switch (index) {
            case 0:
                value = item.number;
                break;

            case 1:
                value = item.roleName;
                break;

            case 2:
                value = item.permissionDes;
                break;

            case 3:
                value = item.showIndex;
                break;

            case 4:
                value = item.createTime;
                break;

            default:
                break;
        }

        var td = document.createElement('td');
        td.innerHTML = value;
        tr.appendChild(td);
    }

    var td = document.createElement('td');
    var index = item.number;
    td.innerHTML = '<button class="show-detail-Button" onclick="showDetailButtonClick(this)">查看</button>';
    tr.appendChild(td);
}

// 全选按钮点击
function selectAllButtonClick() {
    var input = document.querySelector('thead').querySelector('input');

    userList.forEach(element => {
        element.selected = input.checked;
    });

    var inputs = document.querySelector('tbody').querySelectorAll('input');
    inputs.forEach(element => {
        element.checked = input.checked;
    });
}


// 添加按钮点击
function addButtonClick() {
    let arrayLength = userList.length;
    let dateTimeString = dateFormat(new Date());
    const item = new UserItem(arrayLength, "普通角色",
        "admin", arrayLength, dateTimeString);
    userList.push(item);
    addLineData(item);
}

// "编辑" 按钮点击
function modifyButtonClick(params) {
    var trList = document.querySelectorAll('tbody tr');
    var editTdList = [];

    for (var index = 0; index < trList.length; index++) {
        const trElement = trList[index];
        const inputElement = trElement.querySelector('td').querySelector('input');
        if (inputElement.checked == true) {
            editTdList.push(trElement);
            break;
        }
    }
    if (editTdList.length == 0) {
        alert("未选择任何用户")
        return;
    }

    if (editTdList.length > 1) {
        alert("编辑时只能选择一个用户，请取消多选的用户")
        return;
    }

    var userItem = userList[index];
    showDetailPage(userItem, true);
}

// 删除按钮点击
function deleteButtonClick() {
    var trList = document.querySelectorAll('tbody tr');
    var deleteTdList = [];

    for (var index = 0; index < trList.length; index++) {
        const trElement = trList[index];
        const inputElement = trElement.querySelector('td').querySelector('input');
        if (inputElement.checked == true) {
            deleteTdList.push(trElement);
            userList.splice(index, 1);
        }
    }
    if (deleteTdList.length == 0) {
        alert("未选择任何用户")
        return;
    }

    deleteTdList.forEach(element => {
        element.remove();
    });
}


/**
 * “查看按钮”点击
 * @param {*} element 执行该方法的元素，在此页面表示“查看”按钮
 * @returns 
 */
function showDetailButtonClick(element) {
    if (element == undefined) {
        return
    }

    let trElement = element.parentNode.parentNode;

    if (trElement == undefined) {
        return
    }

    let index = trElement.sectionRowIndex;
    let userItem = userList[index];
    showDetailPage(userItem, false);
}


/**
 * 显示详情页
 * @param {*} userItem 用户数据模型 (必填)
 * @param {*} isEdit 输入框是否可编辑，默认false,不可编辑
 */

function showDetailPage(userItem, isEdit = false) {
    let detailPage = document.getElementById("detailPage");

    let roleNameInput = document.getElementById("roleNameInput");
    roleNameInput.value = userItem.roleName;
    roleNameInput.disabled = !isEdit;

    let permissionDesInput = document.getElementById("permissionDesInput");
    permissionDesInput.value = userItem.permissionDes;
    permissionDesInput.disabled = !isEdit;

    let createTimeInput = document.getElementById("createTimeInput");
    createTimeInput.value = userItem.createTime;
    createTimeInput.disabled = !isEdit;

    detailPage.style.display = 'flex';

    let sureButtonElement = document.getElementById("sure-button");
    // 可编辑状态下显示“确定”按钮
    if (isEdit == true) {
        sureButtonElement.style.display = 'block';
    }
    else{
        sureButtonElement.style.display = 'none';
    }
}


// 隐藏详情页面
function hideDetailPage() {
    var detailPage = document.getElementById("detailPage");
    detailPage.style.display = 'none';
}


// 详情页处理可编辑状态时，确定按钮被点击
function sureButtonClick(element) {

    // 获取详情页用户修改的新值
    let roleNameValue = document.getElementById("roleNameInput").value;
    let permissionDesValue = document.getElementById("permissionDesInput").value;
    let createTimeInputValue = document.getElementById("createTimeInput").value;

    // 获取对应的数据模型
    var trList = document.querySelectorAll('tbody tr');
    var modifyItemIndex = -1;

    for (var index = 0; index < trList.length; index++) {
        const trElement = trList[index];
        const inputElement = trElement.querySelector('td').querySelector('input');
        if (inputElement.checked == true) {
            modifyItemIndex = index;
            break;
        }
    }

    hideDetailPage();
    if (modifyItemIndex == -1) {
        alert("用户修改出错");
        return;
    }

    // 从数组里出对应的数据模型
    let userItem = userList[modifyItemIndex];
    if (userItem == undefined) {
        alert("用户修改出错");
        return;
    }

    userItem.roleName = roleNameValue;
    userItem.permissionDes = permissionDesValue;
    userItem.createTime = createTimeInputValue;

    let tr = trList[modifyItemIndex];
    let tdList = tr.querySelectorAll("td");

    tdList[2].innerHTML = userItem.roleName;
    tdList[3].innerHTML = userItem.permissionDes;
    tdList[5].innerHTML = userItem.createTime;

}


// 时间格式化
function dateFormat(date, fmt = 'yyyy-MM-dd hh:mm:ss',) {

    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    let o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds()
    };
    for (let k in o) {
        if (new RegExp(`(${k})`).test(fmt)) {
            let str = o[k] + '';
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : ('00' + str).substr(str.length));
        }
    }
    return fmt;
}

